package m

import (
	"GameServer/Common/utils"
	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"
)

type SingleActivityProgress struct {
	ActId             int64 `bson:"actId"`             // 活动id
	CurRound          int64 `bson:"curRound"`          // 当前处于第几轮
	CurRoundItemCount int64 `bson:"curRoundItemCount"` // 当前轮活动道具数量
	TotalItemCount    int64 `bson:"totalItemCount"`    // 活动道具总量
	GainRoundReward   int64 `bson:"gainRoundReward"`   // 已获得奖励最高轮数
	EndTime           int64 `bson:"endTime"`           // 结束时间
	Close             int64 `bson:"Close"`             // 活动关闭，1表示关闭，0表示开启

	RankId int64 `bson:"rankId"` // 活动排名
}

type UserActivityProgress struct {
	BaseM
	Uid             bson.ObjectId                     `bson:"_id" json:"_id"`
	ActProgressList map[int64]*SingleActivityProgress `bson:"actProgressList" json:"actProgressList"` // 持有的所有活动进度
}

func NewUserActivityProgressData() cache.EntryI {
	return &UserActivityProgress{
		ActProgressList: make(map[int64]*SingleActivityProgress),
	}
}

func (uProgress *UserActivityProgress) Save() (err error) {
	if uProgress.ActProgressList == nil || len(uProgress.ActProgressList) == 0 {
		mdata := make(map[string]interface{}, 0)
		mdata["_id"] = uProgress.Uid
		err = dbmodule.MgoDB.GameDB.Upsert("userActivityProgress", bson.M{"_id": uProgress.Uid}, mdata)
		if err != nil {
			return
		}
		return
	}
	err = dbmodule.MgoDB.GameDB.Upsert("userActivityProgress", bson.M{"_id": uProgress.Uid}, uProgress)
	if err != nil {
		return
	}
	return
}

func (uProgress *UserActivityProgress) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		uProgress.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		uProgress.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "uProgress_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return uProgress.LoadData()
}

//加载数据
func (uProgress *UserActivityProgress) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("userActivityProgress", bson.M{"_id": uProgress.Uid}, nil, &uProgress)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	if uProgress.ActProgressList == nil {
		uProgress.ActProgressList = make(map[int64]*SingleActivityProgress, 0)
	}
	return
}

//更新数据
func (uProgress *UserActivityProgress) Update(val *UserActivityProgress) {
	Cache.Put("userActivityProgress", uProgress.Uid.Hex(), val)
	val.UpdateData()
}

// 获取缓存中的所有活动进度，判断有效性
func (u *User) GetUserActProgress() (r *UserActivityProgress) {
	v, _ := Cache.Get("userActivityProgress", u.Uid.Hex())
	r = v.(*UserActivityProgress)
	if r.ActProgressList == nil {
		r.ActProgressList = make(map[int64]*SingleActivityProgress, 0)
	}
	ActPList := r.ActProgressList
	nowTime := utils.TNow().Unix()
	if len(ActPList) > 0 {
		deleteList := []int64{}
		for K, V := range ActPList {
			temp := V
			if nowTime > temp.EndTime {
				deleteList = append(deleteList, K)
			}
		}
		if len(deleteList) > 0 {
			for _, Value := range deleteList {
				delete(r.ActProgressList, Value)
			}
		}
	}
	r.Update(r)
	return
}

// 获取该UID玩家，所有进度,检查有效性
func GetUserActProgressByUid(uid string) (r *UserActivityProgress) {
	v, _ := Cache.Get("userActivityProgress", uid)
	r = v.(*UserActivityProgress)
	if r.ActProgressList == nil {
		r.ActProgressList = make(map[int64]*SingleActivityProgress, 0)
	}
	if len(r.ActProgressList) > 0 {
		nowTime := utils.TNow().Unix()
		deleteList := []int64{}
		for K, V := range r.ActProgressList {
			temp := V
			if nowTime > temp.EndTime {
				deleteList = append(deleteList, K)
			}
		}
		if len(deleteList) > 0 {
			for _, Value := range deleteList {
				delete(r.ActProgressList, Value)
			}
		}
	}
	r.Update(r)
	return
}

//获取指定id的活动进度，检查有效性
func (progressData *UserActivityProgress) GetActivityProgress(actId int64) (result *SingleActivityProgress, findProgress bool) {
	result, findProgress = progressData.ActProgressList[actId]
	if findProgress == false {
		result = nil
		return
	}
	nowT := utils.TNow().Unix()
	if nowT >= result.EndTime {
		delete(progressData.ActProgressList, actId)
		progressData.Update(progressData)
		result = nil
		findProgress = false
		return
	}
	return
}

//新增、修改活动进度
func (progressData *UserActivityProgress) ActivityProgressUpsetAndUpdate(val *SingleActivityProgress) {
	progressData.ActProgressList[val.ActId] = val
	progressData.Update(progressData)
	return
}

// 删除指定活动进度
func (progressData *UserActivityProgress) DeleteProgress(actId int64) {
	delete(progressData.ActProgressList, actId)
	progressData.Update(progressData)
	return
}
